package com.qu.waibao.account;

import android.content.Intent;
import android.os.CountDownTimer;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.mobileim.IYWLoginService;
import com.alibaba.mobileim.YWAPI;
import com.alibaba.mobileim.YWIMKit;
import com.alibaba.mobileim.YWLoginParam;
import com.alibaba.mobileim.channel.event.IWxCallback;
import com.qu.waibao.AppConfig;
import com.qu.waibao.MainActivity;
import com.qu.waibao.R;
import com.qu.waibao.base.BaseActivity;
import com.qu.waibao.interf.XnetCallBack;
import com.qu.waibao.network.ActionUtil;
import com.qu.waibao.network.NetManager;
import com.qu.waibao.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
public class RegisterActivity extends BaseActivity implements View.OnClickListener{
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_submit)
    TextView tv_submit;
    @BindView(R.id.tv_code)
    TextView tv_code;
    @BindView(R.id.iv_publish)
    ImageView iv_publish;
    @BindView(R.id.cb_pass)
    CheckBox cb_pass;
    @BindView(R.id.cb_again)
    CheckBox cb_again;
    @BindView(R.id.et_phone)
    EditText et_phone;
    @BindView(R.id.et_code)
    EditText et_code;
    @BindView(R.id.et_one_pass)
    EditText et_one_pass;
    @BindView(R.id.et_two_pass)
    EditText et_two_pass;
    private int type = 0;
    private String smscode = "";
    private int card;
    private CountDownTimerUtil countDownTimerUtil;
    @Override
    protected boolean initBundle(Bundle bundle) {
        if(bundle != null){
            type = bundle.getInt("type",0);
        }
        return super.initBundle(bundle);
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_register2;
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        countDownTimerUtil = new CountDownTimerUtil(60000,1000);
        card = AppConfig.getInt("card");
        iv_publish.setVisibility(View.GONE);
        if(type == 1){
            tv_title.setText("注册");
            tv_submit.setText("立即注册");
        }else if(type == 2){
            tv_title.setText("忘记密码");
            tv_submit.setText("确定修改");
        }else if(type == 3){
            tv_title.setText("修改密码");
            tv_submit.setText("确定修改");
            type = 2;
        }
        cb_pass.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked) {
                    et_one_pass.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    et_one_pass.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
            }
        });
        cb_again.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked) {
                    et_two_pass.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    et_two_pass.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
            }
        });
    }
    @OnClick({R.id.ll_back,R.id.tv_code,R.id.tv_submit})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_back:
                finish();
                break;
            case R.id.tv_code:
                String phone = et_phone.getText().toString();
                if(TextUtils.isEmpty(phone)){
                    ToastUtil.show(this,"请输入手机号");
                    return;
                }else if(phone.length() != 11){
                    ToastUtil.show(this,"输入手机号格式有误");
                    return;
                }
                getCode(phone);
                break;
            case R.id.tv_submit:
                String phones = et_phone.getText().toString();
                String code = et_code.getText().toString();
                String onePass = et_one_pass.getText().toString();
                String twoPass = et_two_pass.getText().toString();
                if(TextUtils.isEmpty(phones)){
                    ToastUtil.show(this,"请输入手机号");
                    return;
                }else if(TextUtils.isEmpty(code)){
                    ToastUtil.show(this,"请输入验证码");
                    return;
                }else if(!code.equals(smscode)){
                    ToastUtil.show(this,"输入验证码有误");
                    return;
                }else if(TextUtils.isEmpty(onePass)){
                    ToastUtil.show(this,"请输入密码");
                    return;
                }else if(!twoPass.equals(onePass)){
                    ToastUtil.show(this,"两次密码输入不一致");
                    return;
                }
                register(phones,onePass);
                break;
        }
    }

    public void getCode(String phone){
        Map<String,String> map = new HashMap<>();
        map.put("action", ActionUtil.get_code);
        map.put("phone",phone);
        map.put("type",type+"");
        NetManager.getInstance().request(this, map, true,
                new XnetCallBack() {
                    @Override
                    public void onSuccess(String result, String msg) {
                        countDownTimerUtil.start();
                        tv_code.setEnabled(false);
                        try {
                            JSONObject jsonObject = new JSONObject(result);
                            smscode = jsonObject.optString("smscode");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });
    }

    public void register(String phone,String pwd){
        Map<String,String> map = new HashMap();
        if(type == 2){
            map.put("action", ActionUtil.user_pwd_set);
        }else if(type == 1){
            map.put("action", ActionUtil.user_register_set);
        }
        map.put("phone",phone);
        map.put("pwd",pwd);
        map.put("role",card+"");
        NetManager.getInstance().request(this,map,true,
                new XnetCallBack() {
                    @Override
                    public void onSuccess(String result, String msg) {
                        if(type == 1) {
                            try {
                                JSONObject jsonObject = new JSONObject(result);
                                int role = jsonObject.optInt("role");
                                String state = jsonObject.optString("state_check");
                                String userid = jsonObject.optString("userid");
                                AppConfig.saveInt("card", role);
                                AppConfig.saveString("state_check", state);
                                AppConfig.saveString("userid", userid);
                                initChat(userid, jsonObject.optString("pwd"), role);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }else {
                            ToastUtil.show(RegisterActivity.this,"找回密码成功");
                            finish();
                        }

                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {

                    }

                    @Override
                    public void onFinished() {

                    }
                });
    }

    public class CountDownTimerUtil extends CountDownTimer{

        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *                          {@link #onTick(long)} callbacks.
         */
        public CountDownTimerUtil(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            tv_code.setText(millisUntilFinished/1000+"s");
        }

        @Override
        public void onFinish() {
            tv_code.setEnabled(true);
            tv_code.setText("重新发送");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(countDownTimerUtil != null){
            countDownTimerUtil.cancel();
            countDownTimerUtil = null;
        }
    }

    /**
     * 阿里百川的聊天
     */
    private void initChat(String userid, String pwd, final int role) {
        YWIMKit mIMKit = YWAPI.getIMKitInstance(userid, AppConfig.APP_KEY);
        IYWLoginService loginService = mIMKit.getLoginService();
        YWLoginParam loginParam = YWLoginParam.createLoginParam(userid,pwd);
        loginService.login(loginParam, new IWxCallback() {
            @Override
            public void onSuccess(Object... arg0) {
                ToastUtil.show(RegisterActivity.this, "注册成功");
                if(role == 2){
                    startActivity(new Intent(RegisterActivity.this,XiuAuthonticActivity.class));
                    finish();
                }else if(role == 3){
                    startActivity(new Intent(RegisterActivity.this,ShopAuthonticActivity.class));
                    finish();
                }else {
                    startActivity(new Intent(RegisterActivity.this,MainActivity.class));
                    finish();
                }
            }

            @Override
            public void onProgress(int arg0) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onError(int errCode, String description) {
                //如果登录失败，errCode为错误码,description是错误的具体描述信息
                Log.e("TAG","description----"+description);
            }
        });
    }
}
